package com.haier.dreambox.demo.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.widget.*;
import com.haier.dreambox.demo.BaseActivity;
import com.haier.dreambox.demo.MyApplication;
import com.haier.dreambox.demo.R;
import com.haier.dreambox.demo.bean.BindDeviceRequestBean;
import com.haier.dreambox.demo.bean.BindDeviceResultBean;
import com.haier.dreambox.demo.bean.Event.HaieruDeviceListChangeEvent;
import com.haier.dreambox.demo.bean.GetUserDeviceListRequestBean;
import com.haier.dreambox.demo.bean.GetUserDeviceListResultBean;
import com.haier.dreambox.demo.bean.uplus.*;
import com.haier.dreambox.demo.net.HaierRestClientCommon;
import com.haier.dreambox.demo.persistence.DatabaseHelper;
import com.haier.dreambox.demo.utils.DialogUtil;
import com.haier.dreambox.demo.utils.MyPrefs_;
import com.haier.dreambox.demo.utils.ToastUtils;
import com.haier.uhome.usdk.api.uSDKDevice;
import com.j256.ormlite.dao.RuntimeExceptionDao;
import org.androidannotations.annotations.*;
import org.androidannotations.annotations.rest.RestService;
import org.androidannotations.annotations.sharedpreferences.Pref;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

import java.util.List;


/**
 * Created by smalant on 14/12/26.
 */

@EActivity(R.layout.activity_dev_bind_upload_info)
public class DevBindUploadInfoActivity extends BaseActivity {

    @ViewById(R.id.id_imageButton_common_head_back)
    ImageButton imageButton_back;

    @ViewById(R.id.id_textView_common_head_center_text)
    TextView textView_title;

    @ViewById(R.id.id_button_upload)
    Button button_upload;

    @ViewById(R.id.id_tv_upload_dev_info)
    TextView textView_uploadInfo;

    @Bean
    ToastUtils toastUtils;

    @RestService
    HaierRestClientCommon restClient;

    @Pref
    MyPrefs_ sharePref;

    @App
    MyApplication application;


    @OrmLiteDao(helper = DatabaseHelper.class)
    RuntimeExceptionDao<Device, String> deviceDao;

    ProgressDialog progress;

    @AfterViews
    void main() {
        textView_title.setText("上传绑定");

        StringBuilder sb = new StringBuilder();
        for (uSDKDevice device : sdkManager.getPendingDeviceList()) {
            sb.append(device.toString());
            sb.append("\r\n");
        }
        if (sb.length() > 0) {
            textView_uploadInfo.setText(sb.toString());
        } else {
            button_upload.setEnabled(false);
        }

        progress = DialogUtil.buildProgressDialog(this, "绑定中...", null);
    }

    public void onEvent(HaieruDeviceListChangeEvent event) {

    }

    @Click(R.id.id_button_upload)
    void upload() {
        progress.show();
        bindDevice();
    }

    @Background
    void bindDevice() {
        BindDeviceRequestBean bean = new BindDeviceRequestBean();
        bean.devices = convertToDevice(sdkManager.getPendingDeviceList());
        ResponseEntity<BindDeviceResultBean> result = restClient.bindDevice(bean, sharePref.userId().get());
        handBindResult(result);
    }


    @Background()
    void getUserDevices() {


        GetUserDeviceListRequestBean requestBean = new GetUserDeviceListRequestBean("", "", "", "");

        ResponseEntity<GetUserDeviceListResultBean> resultBean = restClient.getUserDevices(
                application.getSequenceId(),
                requestBean.type,
                requestBean.subType,
                requestBean.specialCode,
                requestBean.typeIdentifier,
                sharePref.userId().get());

        if (resultBean != null && resultBean.getStatusCode() == HttpStatus.OK) {
            GetUserDeviceListResultBean bean = resultBean.getBody();
            if (bean != null && bean.ok()) {

                //缓存
                application.cachHaierUserDevices(bean.devices);

                //存库
                for (Device device : bean.devices) {
                    deviceDao.createOrUpdate(device);
                }

            }
        }

        gotoHomeActivity();

    }

    @UiThread
    void gotoHomeActivity() {
        progress.dismiss();
        HomeActivity_.intent(this).flags(Intent.FLAG_ACTIVITY_CLEAR_TOP).start();
        finish();
    }

    @UiThread
    void handBindResult(ResponseEntity<BindDeviceResultBean> resultBean) {
        if (resultBean.getStatusCode() == HttpStatus.OK) {
            BindDeviceResultBean bean = resultBean.getBody();
            if (bean != null) {
                if (bean.retCode.equals("00000")) {
                    toastUtils.showShort(this, "上传数据成功");
                    sdkManager.clearPendingDeviceList();
                    progress.setMessage("获取设备列表中...");
                    getUserDevices();
                } else {
                    toastUtils.showShort(this, bean.retInfo);
                    progress.dismiss();
                }
            }
        } else {
            toastUtils.showShort(this, "服务器错误码: " + resultBean.getStatusCode());
            progress.dismiss();
        }
    }


    /**
     * uDevice 转换成 Device对象
     *
     * @param pendingDeviceList
     * @return
     */
    private Device[] convertToDevice(List<uSDKDevice> pendingDeviceList) {
        int size = pendingDeviceList.size();
        Device[] devices = new Device[size];
        for (int i = 0; i < size; i++) {
            Device device = new Device();
            uSDKDevice uDevice = pendingDeviceList.get(i);
            device.id = uDevice.getDeviceMac();
            device.mac = uDevice.getDeviceMac();
            device.location = new DeviceLocation("", "", "");
            device.attrs = new DeviceAttribute("", "");
            //String type, String subType, String specialCode, String typeIdentifier
            device.type = new DeviceType(uDevice.getType().getValue(), uDevice.getMiddle_type() + "", uDevice.getSpecial_id(), uDevice.getTypeIdentifier());
            device.status = new DeviceStatus(true);
            //SmartLinkVersion smartlink, String eProtocolVer
            //String smartLinkSoftwareVersion, String smartLinkHardwareVersion,
            // String smartLinkDevfileVersion, String smartLinkPlatform
            SmartLinkVersion smartLinkVersion = new SmartLinkVersion(uDevice.getSmartLinkSoftwareVersion(),
                    uDevice.getEProtocolVer(),
                    uDevice.getSmartLinkDevfileVersion(),
                    uDevice.getSmartLinkPlatform());
            device.version = new DeviceVersion(smartLinkVersion, uDevice.getEProtocolVer());
            device.name = device.mac;
            devices[i] = device;
        }
        return devices;
    }

    @Click(R.id.id_imageButton_common_head_back)
    void backClick() {
        finish();
    }


}
